const queryRoleUrl = '/admin/role/query'
const updateRoleUrl = '/admin/role/update'
// 开启加载
function startLoadSpinner(){
    $('#searchAlertPlaceholder').html(`
        <div class="spinner-border text-center" role="status">
        <span class="visually-hidden">Loading...</span>
    </div>`)
}
// 停止加载
function stopLoadSpinner(){
    $('#searchAlertPlaceholder').html(``)
}
// 修改单个角色信息
function updateRole(code, type){
    let reqData = new Map()
    reqData['type'] = type
    reqData['users'] = [code]
    $.ajax({
        url: updateRoleUrl,
        type: 'POST',
        data: JSON.stringify(reqData),
        dataType: 'JSON',
        contentType: 'application/json;charset=utf-8',
        error: (err) => {
            open_toast('fail', '修改角色信息失败!')
            console.error(err)
        },
        success: (data) => {
            if(data['code'] === 1)
                open_toast('success', data['message'])
            else
                open_toast('fail', data['message'])
        }
    })
}
// 修改多个角色信息
function updateRoles(type){
    let users = []
    // 获取选中的所有用户code
    let reqData = new Map()
    $('.cb_role').each(function(){
        if($(this).prop('checked') === true)
            users.push ($(this).data('code'))
    })
    reqData['type'] = type
    reqData['users'] = users
    $.ajax({
        url: updateRoleUrl,
        type: 'POST',
        data: JSON.stringify(reqData),
        dataType: 'JSON',
        contentType: 'application/json;charset=utf-8',
        error: (err) => {
            open_toast('fail', '修改角色信息失败!')
            console.error(err)
        },
        success: (data) => {
            if(data['code'] === 1)
                open_toast('success', data['message'])
            else
                open_toast('fail', data['message'])
        }
    })
}

// 渲染角色信息
function renderRoleInfo(roleInfo){

    $('#tbody-role').html('')
    $.each(roleInfo, (index, user) =>{
         $('#tbody-role').append(`
          <tr valign="baseline">
                <td><input type="checkbox" class="cb_role" data-code="${user['code']}"></td>
                <td>${user['code']}</td>
                <td>${user['role']['id']}</td>
                <td>${user['role']['roleName']}</td>
                <td>
                     <button class="btn btn-primary" onclick="updateRole('${user['code']}', 'up')">晋升</button>
                     <button class="btn btn-warning" onclick="updateRole('${user['code']}', 'down')">降级</button>
                     <button class="btn btn-danger">删除</button>
                </td>
          </tr>`)
    })
}

function renderRolePageInfo(pageInfo) {
    $('#div-admin-role-page').html('')

    // 首先设置每一页的HTML
    let $perPageInfo = $('<li></li>')
    for (let i in `${pageInfo.navigatepageNums}`) {
        if(i === '0' || i > pageInfo.pages) continue
        $perPageInfo.append(`
        <li>
            <a
                href="${updateCurrentUrlParam('pageNow', i)}" 
                class="page-link d-block text-dark ${i == pageInfo.pageNum ? ' bg-primary' : ''}">
                ${i}
            </a>
        </li>
        `)
    }
    // 如果页数大于1在进行渲染
    if(pageInfo.pages > 1){
        $('#div-admin-role-page').html(`
     <!-- 分页部分 -->
    <h1 class="u-text-sm text-center">第${pageInfo.pageNum}页 共${pageInfo.pages}页</h1>
    <nav aria-label="Page navigation" class="u-text-sm">
        <ul class="pagination justify-content-center">
            <!--首页-->
            <li class="page-item">
                <a class="page-link d-block text-dark" href="${updateCurrentUrlParam('pageNow', pageInfo.navigateFirstPage)}">
                    首页
                </a>
            </li>
            <!--上一页-->
            <li class="page-item">
                <a class="page-link d-block text-dark"
                   href="${updateCurrentUrlParam('pageNow', pageInfo.prePage)}" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            </li>`
            + $perPageInfo.html() +
            `
            <!--下一页-->
            <li class="page-item">
                <a class="page-link d-block text-dark"
                   href="${updateCurrentUrlParam('pageNow', pageInfo.nextPage)}" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
            <!--最后一页-->
            <li class="page-item">
                <a class="page-link d-block text-dark"
                   href="${updateCurrentUrlParam('pageNow', pageInfo.navigateLastPage)}">
                    末页
                </a>
            </li>
        </ul>
    </nav>`)
    }

    $('#textShowResult').html(`共${pageInfo.total}条结果`)
}

function loadRoleData(){
    startLoadSpinner()
    $.ajax({
        url: queryRoleUrl,
        type: 'POST',
        dataType: 'JSON',
        data: getUrlParamToJSON(),
        contentType: 'application/json;charset=UTF-8',
        error: (err) => {
            open_toast('fail', '获取角色信息失败.')
            console.error(err.responseText)
        },
        success: (data) => {
            console.log(data)
            // 设置延迟渲染
            setTimeout(function(){
                if(data['code'] === 1) {
                    renderRoleInfo(data['response']['pageInfo']['list'])
                    renderRolePageInfo(data['response']['pageInfo'])
                    loadRoleDropdown(data['response']['roleInfo'])
                }
                stopLoadSpinner()
            }, 200);
        }
    })
    $('#input-search-role').focus()
}


// 成功弹窗关闭后 -> 关闭模态框，并刷新窗口
$('#toast-success').bind('hidden.bs.toast', function () {
    $('#btn-modal-cancel').click()
    location.reload()
})

// 加载
function loadRoleDropdown(roleInfo){
    $('.role-dropdown-menu').html('')
    $.each(roleInfo, (id, role) => {
        let roleName = role['roleName'];
        $('.role-dropdown-menu').append(`
           <li><a class="dropdown-item" href="${updateCurrentUrlParam('roleName', roleName)}">${roleName}</a></li>
        `)
    })
}
// 全选
$('#cb_all').change(function (){
    $('.cb_role').prop('checked', $(this).prop('checked'))
})
// 搜索
$('#btn-search-role').click(function(){
    let searchText = $('#input-search-role').val();
    if(searchText === '')
        open_toast('warning', '请输入搜索的内容')
    location.href = updateCurrentUrlParam('code', searchText)
})
loadRoleData()

// 按键监听
$(document).keydown(function(event){
    if (event.keyCode === 13) {//回车键登陆
        $('#btn-search-role').click()
    }
});